package com.jing.yao.security.handler;

import com.jing.yao.bean.ResponseBean;
import com.jing.yao.cache.CacheHelper;
import com.jing.yao.cache.RedisKeyEnum;
import com.jing.yao.code.UserCode;
import com.jing.yao.component.constants.BmsConstants;
import com.jing.yao.constant.Enabled;
import com.jing.yao.i18.MessageSourceHolder;
import com.jing.yao.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 登出成功
 *
 * @author lirui
 * @since 2020-06-24
 */
public class YaoLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private CacheHelper cacheHelper;

    @Autowired
    private MessageSourceHolder messageSourceHolder;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding(BmsConstants.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        String token = request.getHeader(JwtUtils.Authorization);
        if (StringUtils.isNotBlank(token)) {
            //删除缓存中的私钥，让登录失效(过期时间为2小时)
            cacheHelper.stringSetExpire(RedisKeyEnum.TOKEN_JWT_EXPIRE.getKey() + token, Enabled.YES.getValue().toString(), 2, TimeUnit.HOURS);
        }

        String code = UserCode.USER_LOGOUT_SUCCESS;
        ResponseBean responseBean = ResponseBean.builder().build();
        responseBean.setMessage(messageSourceHolder.getMessage(code));
        response.getWriter().print(new ObjectMapper().writeValueAsString(responseBean));
    }
}
